package com.friend.chat.page.view.main

import android.Manifest
import android.content.Intent
import android.media.MediaPlayer
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.friend.chat.R
import com.friend.chat.base.BaseFragment
import com.friend.chat.chat.GroupChatActivity
import com.friend.chat.chat.SingleChatActivity
import com.friend.chat.databinding.FragmentChatroomListBinding
import com.friend.chat.db.ChatDatabase
import com.friend.chat.db.dao.MessageDao
import com.friend.chat.page.bean.FriendBean
import com.friend.chat.page.bean.GroupBean
import com.friend.chat.page.bean.RoomBean
import com.friend.chat.page.bean.UserBean
import com.friend.chat.page.view.friend.AddGroupActivity
import com.friend.chat.page.view.friend.QRFriendActivity
import com.friend.chat.page.vm.MainViewModel
import com.friend.chat.page.widget.PopupWindowHelper
import com.friend.chat.utils.EmojiUtil
import com.friend.chat.utils.GlideUtils
import com.friend.chat.utils.SPUtils
import com.friend.chat.websocket.ChatMessageBean
import com.othershe.combinebitmap.CombineBitmap
import com.othershe.combinebitmap.layout.WechatLayoutManager
import com.permissionx.guolindev.PermissionX
import com.yzq.zxinglibrary.android.CaptureActivity
import com.yzq.zxinglibrary.bean.ZxingConfig
import com.yzq.zxinglibrary.common.Constant
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * @des
 * @author batie fancy
 * @date 2023/1/8
 */
class ChatRoomListFragment : BaseFragment<FragmentChatroomListBinding, MainViewModel>() {

    private lateinit var mUserBean: UserBean
    private lateinit var mChatListAdapter: ChatListAdapter
    private var mUserId = ""
    private var mMessageMedia: MediaPlayer? = null


    //数据库
    private lateinit var mMessageDao: MessageDao

    override fun yourViewModel(): MainViewModel = MainViewModel()

    override fun yourViewBing(): FragmentChatroomListBinding {
        return FragmentChatroomListBinding.inflate(layoutInflater)
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser){
            mVModel.getRoomList(mUserId)
        }
    }

    override fun onResume() {
        super.onResume()
        mVModel.getRoomList(mUserId)
    }

    override fun init() {
        mMessageMedia = MediaPlayer.create(requireContext(), R.raw.message)
        mMessageDao = ChatDatabase.getDatabase(requireContext()).messageDao()
        mUserBean = SPUtils.getInstance().getObject("user") as UserBean
        mUserId = mUserBean.uid
        initRecyclerView(mUserBean)

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
    }

    private fun initRecyclerView(userBean: UserBean) {

        val linearLayoutManager = object : LinearLayoutManager(context) {
            override fun canScrollHorizontally(): Boolean {
                return false
            }

            override fun canScrollVertically(): Boolean {
                return true
            }
        }
        mChatListAdapter = ChatListAdapter()
        mViewBing.rvChatList.layoutManager = linearLayoutManager
        mViewBing.rvChatList.adapter = mChatListAdapter
        mChatListAdapter.setOnItemClickListener { adapter, _, position ->
            val roomBean = adapter.data[position] as RoomBean
            if (roomBean.roomType == 0) {
                val friendBean = FriendBean(
                    roomBean.friendHeader,
                    roomBean.friendId,
                    roomBean.friendNickName,
                    roomBean.friendType,
                )
                val intent = Intent(this.context, SingleChatActivity::class.java)
                intent.putExtra("userBean", userBean)
                intent.putExtra("friendBean", friendBean)
                startActivity(intent)
            } else if (roomBean.roomType == 1) {
                val groupBean = GroupBean(
                    roomBean.roomId,
                    roomBean.groupName,
                    roomBean.headers,
                    roomBean.memberIds,
                    "-1"
                )
                GroupChatActivity.open(requireActivity(), mUserBean, groupBean)
            } else {
                //还没整

            }

        }
    }

    override fun setClick() {
        super.setClick()
        //扫描二维码，添加好友
        mViewBing.ivChatroomAdd.setOnClickListener {
            PopupWindowHelper(mViewBing.ivChatroomAdd, R.layout.view_popupwindow_friend)
                .setClickListener(R.id.tv_p_add) {
                    AddGroupActivity.open(requireActivity())
                }
                .setClickListener(R.id.tv_p_qr_show) {
                    QRFriendActivity.open(requireActivity(), mUserBean)
                }
                .setClickListener(R.id.tv_p_qr) {

                    PermissionX.init(this).permissions(Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                        .request { allGranted, _, _ ->
                            val intent = Intent(requireContext(), CaptureActivity::class.java)
                            val config = ZxingConfig()
                            config.isPlayBeep = true //是否播放扫描声音 默认为true
                            config.isShowAlbum = false //是否相册
                            config.isShake = true //是否震动  默认为true

                            config.isDecodeBarCode = true //是否扫描条形码 默认为true

                            config.reactColor = R.color.font_yellow //设置扫描框四个角的颜色 默认为白色

                            // config.frameLineColor = R.color.colorAccent //设置扫描框边框颜色 默认无色

                            config.scanLineColor = R.color.font_yellow //设置扫描线的颜色 默认白色

                            config.isFullScreenScan = false //是否全屏扫描  默认为true  设为false则只会在扫描框中扫描

                            intent.putExtra(Constant.INTENT_ZXING_CONFIG, config)
                            startActivityForResult(intent, 123)

                        }


                }.show(-300, 20)
        }
    }

    override fun onNetListener() {
        super.onNetListener()
        mVModel.roomListResponse.observe(this) {
            val data = it.data
            mChatListAdapter.setList(data)
        }

        mVModel.addFriendResponse.observe(this){
            val data = it.data?:return@observe
            if (data){
                mVModel.toast("添加好友成功")
            }
        }
    }


    class ChatListAdapter :
        BaseQuickAdapter<RoomBean, BaseViewHolder>(R.layout.item_chatroom_list) {
        override fun convert(holder: BaseViewHolder, item: RoomBean) {
            val headerView = holder.getView<ImageView>(R.id.iv_item_chats_header)
            val nameView = holder.getView<TextView>(R.id.tv_item_chats_name)
            val badge = holder.getView<View>(R.id.v_badge)
            if (item.roomType ==0){
                GlideUtils.loadRadiusImg1(headerView, item.friendHeader, 4)
                nameView.text = item.friendNickName
                addChildClickViewIds(R.id.rl_item_chat)
                holder.setText(R.id.tv_item_chats_message,EmojiUtil.getEmojisText(context, item.messageBean.message.toString()))
                if (item.read) {
                    badge.visibility = View.GONE
                } else {
                    badge.visibility = View.VISIBLE
                }
            }else if (item.roomType == 1){

                //头像
                val headerUrls = arrayOfNulls<String>(item.headers.size)
                for ((index, header) in item.headers.withIndex()) {
                    headerUrls[index] = header.header
                }

                val builder = CombineBitmap.init(context)
                    .setLayoutManager(WechatLayoutManager()) // 必选， 设置图片的组合形式，支持WechatLayoutManager、DingLayoutManager
                    .setSize(40) // 必选，组合后Bitmap的尺寸，单位dp
                    .setGap(3) // 单个图片之间的距离，单位dp，默认0dp
                    .setGapColor(ContextCompat.getColor(context, R.color.bg_grey_1)) // 单个图片间距的颜色，默认白色
                    //.setPlaceholder() // 单个图片加载失败的默认显示图片
                    .setUrls(*headerUrls) // 要加载的图片url数组
                    .setImageView(headerView) // 直接设置要显示图片的ImageView
                    // 设置“子图片”的点击事件，需使用setImageView()，index和图片资源数组的索引对应
                    .setOnSubItemClickListener { } // 加载进度的回调函数，如果不使用setImageView()方法，可在onComplete()完成最终图片的显示
                builder.build()
                //名称
                nameView.text = item.groupName
                try {
                    holder.setText(R.id.tv_item_chats_message,EmojiUtil.getEmojisText(context, item.messageBean.message.toString()))
                } catch (e: Exception) {
                }
                if (item.read) {
                    badge.visibility = View.GONE
                } else {
                    badge.visibility = View.VISIBLE
                }
            }

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: ChatMessageBean?) {
        event?.apply {
            if (event.type != 0 && event.type == 1) {
                //0为系统内通讯，5为语音通话
                var newChat = true
                mChatListAdapter.data.forEachIndexed { index, roomBean ->
                    if (event.roomId == roomBean.roomId) {
                        roomBean.messageBean = event
                        roomBean.read = false
                        mChatListAdapter.setData(index, roomBean)
                        newChat = false
                    }
                }
                if (newChat){
                    mVModel.getRoomList(mUserId)
                }

                mMessageMedia?.start()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 123){
            if (data != null) {
                val content: String? = data.getStringExtra(Constant.CODED_CONTENT)
                content?.apply {
                    mVModel.addFriend(mUserId,content)
                }

                mVModel.toast(content?:"")
            }
        }
    }
}